<template>
  <div class="wingknife-process">
    <div class="page-header">
      <div class="header-left">
        <h2>影刀流程管理</h2>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="showCreateDialog">
          <el-icon><Plus /></el-icon>新建影刀流程
        </el-button>
      </div>
    </div>

    <!-- 标签页 -->
    <el-tabs v-model="activeTab" class="process-tabs">
      <el-tab-pane label="流程配置" name="config">
        <!-- 流程配置表格 -->
        <div class="table-container">
          <el-table
            v-loading="loading.config"
            :data="processes"
            border
            style="width: 100%"
          >
            <el-table-column prop="name" label="流程名称" min-width="150">
              <template #default="{ row }">
                <div class="process-name clickable" @click="viewExecutions(row)">
                  <el-icon><Operation /></el-icon>
                  <span>{{ row.name }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
            <el-table-column prop="process_define_id" label="流程定义ID" min-width="180" show-overflow-tooltip />
            <el-table-column prop="output_file_path" label="参数文件路径" min-width="180" show-overflow-tooltip />
            <el-table-column prop="created_at" label="创建时间" width="180">
              <template #default="{ row }">
                {{ formatDate(row.created_at) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="320" fixed="right">
              <template #default="{ row }">
                <el-button-group class="operation-buttons">
                  <el-button type="primary" @click="showEditDialog(row)">
                    <el-icon><Edit /></el-icon>编辑
                  </el-button>
                  <el-button type="success" @click="showRunDialog(row)">
                    <el-icon><VideoPlay /></el-icon>运行
                  </el-button>
                  <el-button type="info" @click="viewExecutions(row)">
                    <el-icon><Document /></el-icon>记录
                  </el-button>
                  <el-button type="danger" @click="handleDelete(row)">
                    <el-icon><Delete /></el-icon>删除
                  </el-button>
                </el-button-group>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>

      <el-tab-pane label="运行记录" name="executions">
        <!-- 当前过滤提示或返回按钮 -->
        <div class="filter-info">
          <div v-if="currentFilterProcessId">
            <el-alert
              type="info"
              :closable="false"
              show-icon
            >
              <template #title>
                当前显示流程 <strong>{{ getProcessName(currentFilterProcessId) }}</strong> 的执行记录
                <el-button type="primary" size="small" text @click="clearExecutionFilter">
                  查看所有记录
                </el-button>
              </template>
            </el-alert>
          </div>
          <div class="return-button">
            <el-button type="primary" @click="activeTab = 'config'">
              <el-icon><Back /></el-icon>返回流程管理
            </el-button>
          </div>
        </div>
        
        <!-- 流程执行记录表格 -->
        <div class="table-container">
          <el-table
            v-loading="loading.executions"
            :data="executions"
            border
            style="width: 100%"
          >
            <el-table-column prop="run_id" label="运行ID" min-width="180" show-overflow-tooltip />
            <el-table-column label="流程名称" min-width="150">
              <template #default="{ row }">
                {{ getProcessName(row.process_id) }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="120">
              <template #default="{ row }">
                <el-tag :type="getStatusType(row.status)">
                  {{ getStatusText(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="started_at" label="开始时间" width="180">
              <template #default="{ row }">
                {{ formatDate(row.started_at) }}
              </template>
            </el-table-column>
            <el-table-column prop="completed_at" label="完成时间" width="180">
              <template #default="{ row }">
                {{ row.completed_at ? formatDate(row.completed_at) : '-' }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" fixed="right">
              <template #default="{ row }">
                <el-button type="primary" @click="showExecutionDetail(row)">
                  <el-icon><View /></el-icon>详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 创建/编辑流程对话框 -->
    <el-dialog
      v-model="dialogs.process"
      :title="editingProcess.id ? '编辑影刀流程' : '新建影刀流程'"
      width="650px"
    >
      <el-form
        ref="processFormRef"
        :model="editingProcess"
        :rules="processRules"
        label-width="100px"
      >
        <el-form-item label="流程名称" prop="name">
          <el-input v-model="editingProcess.name" placeholder="请输入流程名称" />
        </el-form-item>
        <el-form-item label="流程描述" prop="description">
          <el-input
            v-model="editingProcess.description"
            type="textarea"
            :rows="2"
            placeholder="请输入流程描述"
          />
        </el-form-item>
        <el-form-item label="流程定义ID" prop="process_define_id">
          <el-input v-model="editingProcess.process_define_id" placeholder="请输入影刀流程定义ID" />
        </el-form-item>
        <el-form-item label="参数文件路径" prop="output_file_path">
          <el-input v-model="editingProcess.output_file_path" placeholder="请输入完整路径，例如：D:/影刀RPA/参数文件/wingknife_params.json">
            <template #append>
              <el-dropdown @command="selectCommonPath">
                <el-button type="primary">
                  选择
                  <el-icon class="el-icon--right"><ArrowDown /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="D:/影刀RPA/参数文件/wingknife_params.json">影刀默认路径</el-dropdown-item>
                    <el-dropdown-item command="D:/影刀RPA/参数文件/{{流程名称}}.json">影刀自定义路径</el-dropdown-item>
                    <el-dropdown-item command="D:/TWRPA/output/params.json">TWRPA默认路径</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-input>
          <div class="form-item-tips">
            <small>
              请输入完整路径，包括文件名(.json)。请确保路径格式正确且目录可写入，否则将无法保存。
              <br>示例: D:/影刀RPA/参数文件/wingknife_params.json
            </small>
          </div>
        </el-form-item>
        <el-form-item label="流程参数" prop="parameters">
          <div class="parameters-container">
            <el-alert
              type="info"
              show-icon
              :closable="false"
              title="以JSON格式配置流程参数，包括收货地址、超市名称等"
            />
            <el-input
              v-model="parametersJson"
              type="textarea"
              :rows="10"
              placeholder="请以JSON格式输入参数，例如：{'收货地址': '北影小区', '超市名称': '物美超市'}"
              @input="validateJSON"
            />
            <div v-if="jsonError" class="json-error">
              <el-alert
                type="error"
                show-icon
                :closable="false"
                :title="jsonError"
              />
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogs.process = false">取消</el-button>
          <el-button type="primary" :loading="loading.submit" @click="handleSubmitProcess">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 运行流程对话框 -->
    <el-dialog
      v-model="dialogs.run"
      title="运行影刀流程"
      width="550px"
    >
      <div v-if="currentProcess" class="run-dialog">
        <p><strong>流程名称：</strong>{{ currentProcess.name }}</p>
        <p><strong>流程定义ID：</strong>{{ currentProcess.process_define_id }}</p>
        
        <el-divider content-position="center">参数配置</el-divider>
        
        <div class="parameters-container">
          <!-- 查询超市流程 -->
          <template v-if="currentProcess.name === '查询超市'">
            <el-form :model="runForm" label-width="100px">
              <el-form-item label="收货地址">
                <el-input v-model="runForm.address" placeholder="请输入收货地址" />
              </el-form-item>
            </el-form>
          </template>
          
          <!-- 查询商品流程 -->
          <template v-else-if="currentProcess.name === '查询商品'">
            <el-form :model="runForm" label-width="100px">
              <el-form-item label="选择超市">
                <el-select
                  v-model="runForm.storeId"
                  placeholder="请选择超市"
                  style="width: 100%"
                  :loading="storeListLoading"
                  filterable
                  :style="{ height: '50px' }"
                >
                  <el-option
                    v-for="store in storeList"
                    :key="store.id"
                    :label="store.name"
                    :value="store.id"
                    :style="{ height: '50px' }"
                  >
                    <div class="store-option">
                      <div class="store-name">{{ store.name }}</div>
                      <div class="store-address">{{ store.address }}</div>
                    </div>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </template>
          
          <!-- 其他流程保持原有的JSON编辑界面 -->
          <template v-else>
            <el-alert
              type="info"
              show-icon
              :closable="false"
              title="您可以添加或修改运行参数"
            />
            <el-input
              v-model="runParametersJson"
              type="textarea"
              :rows="10"
              placeholder="流程将使用这些参数运行"
              @input="validateRunJSON"
            />
            <div v-if="runJsonError" class="json-error">
              <el-alert
                type="error"
                show-icon
                :closable="false"
                :title="runJsonError"
              />
            </div>
          </template>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogs.run = false">取消</el-button>
          <el-button type="primary" :loading="loading.run" @click="handleRun">
            运行
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 执行详情对话框 -->
    <el-dialog
      v-model="dialogs.execution"
      title="执行详情"
      width="750px"
    >
      <div v-if="currentExecution" class="execution-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="运行ID" span="2">{{ currentExecution.run_id }}</el-descriptions-item>
          <el-descriptions-item label="流程名称">{{ getProcessName(currentExecution.process_id) }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(currentExecution.status)">
              {{ getStatusText(currentExecution.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="开始时间">{{ formatDate(currentExecution.started_at) }}</el-descriptions-item>
          <el-descriptions-item label="完成时间">{{ currentExecution.completed_at ? formatDate(currentExecution.completed_at) : '-' }}</el-descriptions-item>
        </el-descriptions>

        <el-divider content-position="center">运行参数</el-divider>
        
        <el-input
          type="textarea"
          :model-value="JSON.stringify(currentExecution.parameters || {}, null, 2)"
          :rows="12"
          readonly
        />

        <el-divider content-position="center" v-if="currentExecution.result">执行结果</el-divider>
        
        <el-input
          v-if="currentExecution.result"
          type="textarea"
          :model-value="JSON.stringify(currentExecution.result || {}, null, 2)"
          :rows="8"
          readonly
        />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, Edit, Delete, Operation, VideoPlay, View, Document, Back, ArrowDown
} from '@element-plus/icons-vue'
import {
  getWingknifeProcessList,
  getWingknifeProcessDetail,
  createWingknifeProcess,
  updateWingknifeProcess,
  deleteWingknifeProcess,
  runWingknifeProcess,
  getWingknifeExecutionList,
  getWingknifeExecutionDetail
} from '@/api/wingknife'
import { getShopList } from '@/api/shop'
import { useRouter } from 'vue-router'
import { sanitizeObjectKeys } from '@/utils'

// 初始化router
const router = useRouter()

// 状态变量
const activeTab = ref('config')
const processes = ref([])
const executions = ref([])
const editingProcess = ref({
  name: '',
  description: '',
  process_define_id: '',
  parameters: {},
  output_file_path: ''
})
const parametersJson = ref('{}')
const jsonError = ref('')
const runParametersJson = ref('{}')
const runJsonError = ref('')
const currentProcess = ref(null)
const currentExecution = ref(null)

// 加载状态
const loading = reactive({
  config: false,
  executions: false,
  submit: false,
  run: false
})

// 对话框显示状态
const dialogs = reactive({
  process: false,
  run: false,
  execution: false
})

// 表单引用
const processFormRef = ref(null)

// 表单验证规则
const processRules = {
  name: [
    { required: true, message: '请输入流程名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  process_define_id: [
    { required: true, message: '请输入流程定义ID', trigger: 'blur' }
  ],
  output_file_path: [
    { required: true, message: '请输入参数文件保存路径', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        // 检查路径格式
        if (!value) {
          callback(new Error('请输入参数文件保存路径'));
          return;
        }
        
        // 转换分隔符为标准格式
        const standardPath = value.replace(/\\/g, '/');
        
        // 检查是否包含文件名
        if (!standardPath.includes('.json')) {
          callback(new Error('路径必须包含.json文件名'));
          return;
        }
        
        // 检查路径格式是否合法
        try {
          // 简单检查路径是否有效
          if (standardPath.includes('..') || !standardPath.includes('/')) {
            callback(new Error('路径格式不正确'));
            return;
          }
          
          callback(); // 验证通过
        } catch (e) {
          callback(new Error('路径格式不正确: ' + e.message));
        }
      },
      trigger: 'blur'
    }
  ]
}

// 监听标签页切换
watch(activeTab, (newValue) => {
  if (newValue === 'config') {
    fetchProcessList()
  } else if (newValue === 'executions') {
    fetchExecutionList()
  }
})

// 初始化
onMounted(() => {
  fetchProcessList()
})

// 获取所有流程
const fetchProcessList = async () => {
  try {
    loading.config = true
    const data = await getWingknifeProcessList()
    processes.value = data
  } catch (error) {
    console.error('获取影刀流程列表失败:', error)
    ElMessage.error('获取影刀流程列表失败')
  } finally {
    loading.config = false
  }
}

// 获取执行记录
const fetchExecutionList = async (processId = null) => {
  try {
    loading.executions = true
    const data = await getWingknifeExecutionList(processId)
    executions.value = data
    
    // 如果提供了流程ID，设置过滤状态
    if (processId) {
      currentFilterProcessId.value = processId
    } else {
      currentFilterProcessId.value = null
    }
  } catch (error) {
    console.error('获取执行记录失败:', error)
    ElMessage.error('获取执行记录失败')
  } finally {
    loading.executions = false
  }
}

// 日期格式化
const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 获取执行状态类型
const getStatusType = (status) => {
  const types = {
    'pending': 'info',
    'running': 'warning',
    'completed': 'success',
    'failed': 'danger'
  }
  return types[status] || 'info'
}

// 获取执行状态文本
const getStatusText = (status) => {
  const texts = {
    'pending': '等待中',
    'running': '运行中',
    'completed': '已完成',
    'failed': '失败'
  }
  return texts[status] || status
}

// 根据流程ID获取流程名称
const getProcessName = (processId) => {
  const process = processes.value.find(p => p.id === processId)
  return process ? process.name : `流程 #${processId}`
}

// 显示创建对话框
const showCreateDialog = () => {
  const processId = generateUUID()
  
  // 创建一个干净的模板对象
  const templateProcess = {
    name: '',
    description: '',
    process_define_id: processId,
    output_file_path: 'D:/影刀RPA/参数文件/wingknife_params.json',
    parameters: {
      "收货地址": "北影小区",
      "超市名称": "物美超市",
      "流程定义id": processId,
      "运行id": "",
      "输出目录": "D:/影刀RPA/参数文件"
    }
  };
  
  // 使用工具函数确保所有键都是字符串
  editingProcess.value = sanitizeObjectKeys(templateProcess);
  
  // 转换参数为JSON
  parametersJson.value = JSON.stringify(editingProcess.value.parameters || {}, null, 2)
  jsonError.value = ''
  dialogs.process = true
}

// 生成UUID
const generateUUID = () => {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    const r = Math.random() * 16 | 0
    const v = c === 'x' ? r : (r & 0x3 | 0x8)
    return v.toString(16)
  })
}

// 显示编辑对话框
const showEditDialog = (process) => {
  // 使用工具函数处理process数据
  editingProcess.value = sanitizeObjectKeys(process);
  
  // 转换参数为JSON
  parametersJson.value = JSON.stringify(editingProcess.value.parameters || {}, null, 2)
  jsonError.value = ''
  dialogs.process = true
}

// 验证JSON
const validateJSON = (value) => {
  try {
    const parsed = JSON.parse(value)
    // 使用工具函数确保所有键都是字符串
    editingProcess.value.parameters = sanitizeObjectKeys(parsed);
    jsonError.value = ''
  } catch (error) {
    jsonError.value = 'JSON格式错误: ' + error.message
  }
}

// 验证运行参数JSON
const validateRunJSON = (value) => {
  try {
    const parsed = JSON.parse(value)
    // 使用工具函数确保所有键都是字符串
    const cleanParsed = sanitizeObjectKeys(parsed);
    // 存储清理后的参数
    runParametersJson.value = JSON.stringify(cleanParsed, null, 2);
    runJsonError.value = ''
  } catch (error) {
    runJsonError.value = 'JSON格式错误: ' + error.message
  }
}

// 提交流程表单
const handleSubmitProcess = async () => {
  if (jsonError.value) {
    ElMessage.error('请修正JSON格式错误')
    return
  }

  try {
    await processFormRef.value.validate()
    
    loading.submit = true
    
    // 更新参数对象 - 从JSON编辑器中获取最新值
    try {
      if (parametersJson.value) {
        const parsed = JSON.parse(parametersJson.value);
        editingProcess.value.parameters = sanitizeObjectKeys(parsed);
      }
    } catch (e) {
      console.error('参数解析失败:', e);
      ElMessage.error('参数JSON格式错误，请检查');
      loading.submit = false;
      return;
    }
    
    // 1. 创建一个干净的数据对象
    const cleanedProcess = {
      name: editingProcess.value.name || '',
      description: editingProcess.value.description || '',
      process_define_id: editingProcess.value.process_define_id || '',
      output_file_path: editingProcess.value.output_file_path.replace(/\\/g, '/') || '',
      created_by: null
    }
    
    // 2. 单独处理参数对象，确保它是一个简单对象
    const sanitizedParams = sanitizeObjectKeys(editingProcess.value.parameters || {});
    
    // 处理参数中的路径
    if (sanitizedParams["输出目录"]) {
      sanitizedParams["输出目录"] = sanitizedParams["输出目录"].replace(/\\/g, '/');
    }
    
    // 确保参数不是数组，如果是则转换为对象
    if (Array.isArray(sanitizedParams)) {
      cleanedProcess.parameters = {};
    } else {
      cleanedProcess.parameters = sanitizedParams;
    }
    
    // 3. 记录发送的数据，便于调试
    console.log('发送流程数据:', JSON.stringify(cleanedProcess));
    
    try {
      if (editingProcess.value.id) {
        // 更新现有流程
        await updateWingknifeProcess(editingProcess.value.id, cleanedProcess)
        ElMessage.success('流程更新成功')
      } else {
        // 创建新流程
        await createWingknifeProcess(cleanedProcess)
        ElMessage.success('流程创建成功')
      }
      
      dialogs.process = false
      fetchProcessList()
    } catch (error) {
      console.error('API调用失败:', error);
      
      if (error.response) {
        console.error('服务器响应:', {
          status: error.response.status,
          headers: error.response.headers,
          data: error.response.data
        });
        
        // 422错误通常是验证错误，显示详细信息
        if (error.response.status === 422) {
          const detail = error.response.data?.detail;
          let errorMsg = '数据验证失败';
          
          if (detail) {
            // 如果是字符串，直接显示
            if (typeof detail === 'string') {
              errorMsg = detail;
            } 
            // 如果是数组，格式化显示
            else if (Array.isArray(detail)) {
              errorMsg = detail.map(err => {
                const field = err.loc ? err.loc[err.loc.length - 1] : '';
                return `${field}: ${err.msg}`;
              }).join('; ');
            }
          }
          
          ElMessage.error(errorMsg);
          return; // 不再抛出错误
        }
      }
      
      throw error; // 重新抛出错误，让外层catch处理
    }
  } catch (error) {
    console.error('保存流程失败:', error)
    let errorMessage = '保存流程失败';
    
    // 尝试从响应中提取详细错误信息
    if (error.response?.data?.detail) {
      if (typeof error.response.data.detail === 'string') {
        errorMessage += ': ' + error.response.data.detail;
      } else if (Array.isArray(error.response.data.detail)) {
        // 处理验证错误数组
        errorMessage += ': ' + error.response.data.detail.map(err => 
          `${err.loc && err.loc.join('.') || ''} - ${err.msg || JSON.stringify(err)}`
        ).join('; ');
      } else {
        errorMessage += ': ' + JSON.stringify(error.response.data.detail);
      }
    } else if (error.message) {
      errorMessage += ': ' + error.message;
    }
    
    ElMessage.error(errorMessage)
  } finally {
    loading.submit = false
  }
}

// 删除流程
const handleDelete = async (process) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除流程 "${process.name}" 吗？相关的执行记录也将被删除。`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteWingknifeProcess(process.id)
    ElMessage.success('流程删除成功')
    
    fetchProcessList()
    // 如果在执行记录标签页，也刷新执行记录
    if (activeTab.value === 'executions') {
      fetchExecutionList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除流程失败:', error)
      ElMessage.error('删除流程失败: ' + (error.response?.data?.detail || error.message))
    }
  }
}

// 在 script setup 部分修改
const runForm = reactive({
  address: '',
  storeId: ''
})

// 修改超市列表数据为响应式引用
const storeList = ref([])
const storeListLoading = ref(false)

// 添加获取超市列表的函数
const fetchStoreList = async () => {
  storeListLoading.value = true
  try {
    const response = await getShopList({
      status: 'Y',  // 只获取启用的店铺
      page: 1,
      pageSize: 100  // 获取足够多的店铺
    })
    storeList.value = response.items.map(shop => ({
      id: shop.id.toString(),
      name: shop.shop_name,
      address: shop.shop_address || shop.shipping_address || '暂无地址'
    }))
  } catch (error) {
    console.error('获取店铺列表失败:', error)
    ElMessage.error('获取店铺列表失败')
  } finally {
    storeListLoading.value = false
  }
}

// 修改 showRunDialog 函数
const showRunDialog = async (process) => {
  // 使用工具函数处理process数据
  currentProcess.value = sanitizeObjectKeys(process);

  // 先弹出弹窗
  dialogs.run = true;

  // 根据流程名称初始化表单
  if (process.name === '查询超市') {
    runForm.address = process.parameters['收货地址'] || '';
  } else if (process.name === '查询商品') {
    // 异步加载店铺列表
    fetchStoreList().then(() => {
      runForm.storeId = process.parameters['id'] || '';
    });
  } else {
    // 其他流程保持原有的JSON编辑界面
    runParametersJson.value = JSON.stringify(currentProcess.value.parameters || {}, null, 2);
    runJsonError.value = '';
  }
};

// 修改 handleRun 函数
const handleRun = async () => {
  try {
    loading.run = true;
    
    // 创建干净的参数对象
    const cleanParams = {};
    
    if (currentProcess.value.name === '查询超市') {
      // 复制原始参数
      Object.keys(currentProcess.value.parameters || {}).forEach(key => {
        cleanParams[String(key)] = currentProcess.value.parameters[key];
      });
      // 更新收货地址
      cleanParams['收货地址'] = runForm.address;
    } else if (currentProcess.value.name === '查询商品') {
      // 复制原始参数
      Object.keys(currentProcess.value.parameters || {}).forEach(key => {
        cleanParams[String(key)] = currentProcess.value.parameters[key];
      });
      // 更新超市ID
      cleanParams['id'] = runForm.storeId;
    } else {
      // 其他流程保持原有的参数处理逻辑
      if (runJsonError.value) {
        ElMessage.error('请修正JSON格式错误');
        return;
      }
      
      // 解析运行参数，合并原始参数和新参数
      const originalParams = currentProcess.value.parameters || {};
      const additionalParams = JSON.parse(runParametersJson.value);
      
      // 添加原始参数，确保键为字符串
      Object.keys(originalParams).forEach(key => {
        let value = originalParams[key];
        if (typeof value === 'string' && value.includes('\\')) {
          value = value.replace(/\\/g, '/');
        }
        cleanParams[String(key)] = value;
      });
      
      // 添加新参数，确保键为字符串
      Object.keys(additionalParams).forEach(key => {
        let value = additionalParams[key];
        if (typeof value === 'string' && value.includes('\\')) {
          value = value.replace(/\\/g, '/');
        }
        cleanParams[String(key)] = value;
      });
    }
    
    // 使用工具函数确保所有键都是字符串
    const sanitizedParams = sanitizeObjectKeys(cleanParams);
    
    // 调用运行API
    await runWingknifeProcess(currentProcess.value.id, sanitizedParams);
    
    ElMessage.success(`流程 "${currentProcess.value.name}" 开始运行`);
    dialogs.run = false;
    
    // 切换到执行记录标签并刷新
    if (activeTab.value === 'executions') {
      await fetchExecutionList();
    } else {
      activeTab.value = 'executions';
      await router.push({
        path: '/wingknife/executions',
        query: {
          processId: currentProcess.value.id,
          processName: currentProcess.value.name,
          refresh: 'true'
        }
      });
    }
  } catch (error) {
    console.error('运行流程失败:', error);
    ElMessage.error('运行流程失败: ' + (error.response?.data?.detail || error.message));
  } finally {
    loading.run = false;
  }
}

// 显示执行详情
const showExecutionDetail = async (execution) => {
  try {
    const data = await getWingknifeExecutionDetail(execution.id)
    
    // 使用工具函数完全净化从API获取的数据，确保所有对象键都是字符串
    currentExecution.value = sanitizeObjectKeys(data);
    
    dialogs.execution = true
  } catch (error) {
    console.error('获取执行详情失败:', error)
    ElMessage.error('获取执行详情失败')
  }
}

// 查看执行记录
const viewExecutions = (process) => {
  router.push({
    path: '/wingknife/executions',
    query: {
      processId: process.id,
      processName: process.name
    }
  })
}

// 当前过滤的流程ID
const currentFilterProcessId = ref(null)

// 清除执行记录过滤
const clearExecutionFilter = () => {
  currentFilterProcessId.value = null
  fetchExecutionList()
}

// 选择常用目录
const selectCommonPath = (path) => {
  // 检查是否有动态替换标记
  if (path.includes('{{流程名称}}') && editingProcess.value.name) {
    // 替换掉动态标记
    path = path.replace('{{流程名称}}', editingProcess.value.name);
  }
  editingProcess.value.output_file_path = path;
}
</script>

<style scoped>
/* 添加店铺选项样式 */
.store-option {
  padding: 8px 0;
  min-height: 44px;
}

.store-name {
  font-size: 14px;
  line-height: 1.4;
}

.store-address {
  font-size: 12px;
  color: #b0b3b8;
  line-height: 1.2;
  margin-top: 2px;
}

/* 修改下拉选项的样式 */
:deep(.el-select-dropdown__item) {
  padding: 10px 12px;
  min-height: 44px;
}

:deep(.el-select-dropdown__item.selected) .store-name {
  color: var(--el-color-primary);
}

:deep(.el-select-dropdown__item.selected) .store-address {
  color: var(--el-color-primary-light-5);
}

</style> 